package haoyc.handler;

import haoyc.entity.SimpleKeyEvent;
import haoyc.server.RobotClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * @author Memory
 * @version 1.0
 * @date 2021/11/23
 */

@Slf4j
@ChannelHandler.Sharable
public class KeyEventHandler extends SimpleChannelInboundHandler<SimpleKeyEvent> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SimpleKeyEvent event) {
        try {
            /**
             * 键盘事件
             */
            Robot robot = RobotClient.getRobot();
            switch (event.getKeyId()) {
                case KeyEvent.KEY_PRESSED:
                    robot.keyPress(event.getKeyCode());
                    break;
                case KeyEvent.KEY_RELEASED:
                    robot.keyRelease(event.getKeyCode());
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(), cause);
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        super.channelReadComplete(ctx);
    }
}
